﻿using AiMoWindows.MainActions.Mode;

namespace AiMoWindows.CodeScripts.Init
{
    class UsingCodeController
    {
        readonly CodeBlock m_UsingCode = CodeBlock.Default;

        readonly Dictionary<string, string> m_InputUsings = new Dictionary<string, string>();

        ScriptComplileMode m_PreviousCompileMode = ScriptComplileMode.Unset;
        public CodeBlock CurrentUsingCode(ScriptComplileMode compileMode)
        {
            if (m_PreviousCompileMode == compileMode) return m_UsingCode;
            Dictionary<string, string> result = new Dictionary<string, string>()
            {
                {"System","using System;" },
                {"System.Linq","using System.Linq;" },
                {"System.Collections.Generic","using System.Collections.Generic;" },
            };
            foreach (var kvp in m_InputUsings)
            {
                result.TryAdd(kvp.Key, kvp.Value);
            }
            switch (compileMode)
            {
                case ScriptComplileMode.RhinoScript:
                    result.TryAdd("AiMoCore", "using AiMoCore;");
                    result.TryAdd("Rhino", "using Rhino;");
                    result.TryAdd("Rhino.Geometry", "using Rhino.Geometry;");
                    break;
                case ScriptComplileMode.GrasshopperScript:
                    result.TryAdd("AiMoCore", "using AiMoCore;");
                    result.TryAdd("Rhino", "using Rhino;");
                    result.TryAdd("Rhino.Geometry", "using Rhino.Geometry;");
                    result.TryAdd("Grasshopper", "using Grasshopper;");
                    break;
            }
            m_UsingCode.UpdateLines(result.OrderBy(x => x.Key).Select(x => x.Value));
            m_PreviousCompileMode = compileMode;
            return m_UsingCode;
        }


        public void Update(IEnumerable<string>? lines)
        {

            m_InputUsings.Clear();
            if (lines == null) return;
            foreach (string line in lines)
            {
                string line2 = line.Trim();
                if ((line2.StartsWith("using") && line2.Contains(';')))
                {
                    int end = line2.IndexOf(';');
                    int start = line2.IndexOf("using ") + 6;
                    string key = line2[start..end];
                    m_InputUsings.TryAdd(key, line2);
                }
            }
            m_PreviousCompileMode = ScriptComplileMode.Unset;
        }

    }
}
